import {Component, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import * as echarts from 'echarts/lib/echarts';
import {FetchService} from "../../../core/net/fetch.service";
import * as _ from "lodash";
import {UtilService} from "../../../core/util/util.service";

@Component({
  selector: 'app-realtime-overview-management',
  templateUrl: './realtime-overview.component.html',
  styleUrls: ['./realtime-overview.component.scss']
})
export class RealtimeOverviewComponent implements OnInit {
  qssyTableData;
  gyysTableData;
  mapChartOption;
  basePieChartOption = {
    title: {
      zlevel: 0,
      text: '',
      rich: {
        name: {
          color: '#909399',
          fontSize: 14,
          fontWeight: 'normal',
          lineHeight: 18,
        },
        value: {
          color: '#3d3d3d',
          fontSize: 18,
          fontWeight: 'bold',
          lineHeight: 22,
        },
      },
      top: 'center',
      left: '105',
      textAlign: 'center',
      textStyle: {
        rich: {
          name: {
            color: '#909399',
            fontSize: 14,
            fontWeight: 'normal',
            lineHeight: 18,
          },
          value: {
            color: '#3d3d3d',
            fontSize: 18,
            fontWeight: 'bold',
            lineHeight: 22,
          },
        },
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    color: ['#637efe', '#ffc209', '#0094f0', '#d2e2ff'],
    legend: {
      orient: 'vertical',
      x: 'right',
      data: [],
      itemGap: 25,
      top: 'middle',
      align: 'left',
      icon: 'circle',
      // formatter: name =>  {
      //     return name;
      // }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['55%', '69%'],
        center: [110, '50%'],
        stillShowZeroSum: false,
        avoidLabelOverlap: false,
        zlevel: 1,
        label: {
          normal: {
            padding: [10, 10, 10, 10],
            backgroundColor: '#f0f0f0',
            show: false,
            position: 'center',
            rich: {
              name: {
                color: '#909399',
                fontSize: 14,
                fontWeight: 'normal',
                lineHeight: 18,
              },
              value: {
                color: '#3d3d3d',
                fontSize: 18,
                fontWeight: 'bold',
                lineHeight: 22,
              },
            },
          },
          emphasis: {
            show: true,
            textStyle: {
              fontSize: '16',
              fontWeight: 'bold'
            }
          }
        },
        labelLine: {
          normal: {
            show: false
          }
        },
        data: []
      }
    ]
  };
  pieChartOpt1;
  pieChartOpt2;
  pieTotal1 = 0;
  pieTotal2 = 0;

  baseBarChartOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    color: ['#81d5ef', '#7980f1', '#0d83bf', '#89b0ae', '#4b707b'],
    legend: {
      top: 0,
      data: []
    },
    grid: {
      top: 30,
      right: '4%',
      bottom: 60,
    },
    xAxis: [
      {
        type: 'category',
        axisLabel: {
          interval: 0,
          rotate: 30
        },
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: []
  };
  barChartOpt1;
  baseBarChartOption2;
  ljhs;

  constructor(
    private router: Router,
    private util: UtilService,
    private fetchService: FetchService,
  ) {
  }

  ngOnInit(): void {
    this.getMapData();
    this.initPieChartData();
    this.initBarChartData();
    this.getTableData();

    // 累计耗水
    this.fetchService.post<any>('wrs/wrsBrstadia/sumUseFlux', {}).subscribe(res => {
      this.ljhs = res.val;
    });
  }

  getMapData() {
    this.fetchService.get<any>('assets/data/zx/features.json').subscribe(geoJson => {
      echarts.registerMap('ningxia', geoJson, {});
      this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: 27}).subscribe(res => {
        const data = [
          {name: '青铜峡市', value: 20057.34},
          {name: '永宁县', value: 15477.48},
          {name: '兴庆区', value: 31686.1},
          {name: '金凤区', value: 6992.6},
          {name: '西夏区', value: 44045.49},
          {name: '贺兰县', value: 40689.64},
          {name: '平罗县', value: 37659.78},
          {name: '惠农区', value: 45180.97},
          {name: '大武口区', value: 55204.26},
          {name: '农垦系统', value: 21900.9},
          {name: '监狱局', value: 4918.26},
          {name: '灵武市', value: 5881.84},
          {name: '利通区', value: 4178.01},
          {name: '中卫县', value: 2227.92},
          {name: '中宁县', value: 2180.98},
          {name: '海原县', value: 9172.94},
          {name: '同心县', value: 3368},
          {name: '吴忠市', value: 806.98}
        ];
        this.mapChartOption = {
          tooltip: {
            trigger: 'item',
            // formatter: '{b}<br/>灌溉面积：{c} 万亩'
            formatter: (params) => {
              if (!params.data) {
                return '';
              } else {
                return `
                    ${params.data.name}<br/>
                    用水量：${params.data.areaVal} 亿m³
                    `;
              }
            }
          },
          visualMap: {
            min: 0,
            max: 100,
            text: ['最大', '最小'],
            realtime: false,
            calculable: true,
            inRange: {
              color: ['#1371F0', '#0B96EE', '#27CAE1']
            }
          },
         /* visualMap: {
            show: false,
            inRange: {
              color: ['#4975F6']
            }
          },*/
         /* dataRange: {
            x: 'left',
            y: 'center',
            splitList: [
              {start: 0.8, label: '80%以上', color: '#FF6699'},
              {start: 0.6, end: 0.8, label: '60-80%', color: '#CC3300'},
              {start: 0.4, end: 0.6, label: '40-60%', color: '#F7BB37'},
              {start: 0.3, end: 0.4, label: '30-40%', color: '#3BAE56'},
              {start: 0.2, end: 0.3, label: '20-30%', color: '#92D050'},
              {start: 0.1, end: 0.2, label: '10-20%', color: '#3899FF'},
              {start: 0, end: 0.1, label: '0-10%', color: '#BFBFBF'}
            ],
            textStyle: {
              color: '#3899FF' // 值域文字颜色
            },
            selectedMode: false,
            color: ['#E0022B', '#E09107', '#A3E00B']
          },*/
          series: [
            {
              name: '引黄灌区',
              type: 'map',
              mapType: 'ningxia',
              aspectScale: 1,  // 地图长度比
              label: {
                normal: {

                  show: true,
                  textStyle: {
                    color: '#fff',
                    fontSize: 10

                  }
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    color: '#fff',
                    fontSize: 13
                  },
                  areaColor: '#f46d43'
                }
              },
              itemStyle: {
                normal: {
                  areaColor: '#4975F6',
                  borderColor: '#55D2FF',
                  borderWidth: 2
                },
                emphasis: { // 鼠标移入高亮显颜色
                  areaColor: '#06affb'
                }
              },
              zoom: 1.2, // 当前视角的缩放比例
              roam: true, // 是否开启平游或缩放
              scaleLimit: { // 滚轮缩放的极限控制
                min: 1,
                max: 2
              },
              data: res
            }
          ]
        };
      });

    });
  }

  goPage() {
    this.router.navigate(['/realtime-control/dispatch-zx']);
  }

  chartClick(param) {
    console.log(param);
  }

  initPieChartData(): void {
    // 各业用水
    this.fetchService.post('sys/sysApiInfo/queryApiData', {apicode: 25}).subscribe(res => {
      const resData = [{
        "name": "农业用水",
        "totalVal": 54.497,
        "todayVal": 0.17
      }, {
        "name": "生态用水",
        "totalVal": 2.408,
        "todayVal": 0.01
      }, {
        "name": "工业用水",
        "totalVal": 4.786,
        "todayVal": 0.00
      }, {
        "name": "生活用水",
        "totalVal": 3.634,
        "todayVal": 0.00
      }];
      this.pieTotal1 = this.util.sum(this.util.getItemValues(resData, 'totalVal', true));
      this.pieChartOpt1 = this.getPieChartData(resData, '用水指标', '各业用水指标', '亿方', this.pieTotal1, ['#637efe', '#7ed6f1', '#0094f0', '#d2e2ff']);
      console.log(this.pieChartOpt1);
    });

    // 取水水源分布
    this.fetchService.post('sys/sysApiInfo/queryApiData', {apicode: 26}).subscribe(res => {
      this.qssyTableData = res;
      this.pieTotal2 = this.util.sum(this.util.getItemValues(res, 'useVal', true));
      this.pieChartOpt2 = this.getPieChartData2(res, '取水指标', '取水水源分布', '亿方', this.pieTotal2, ['#637efe', '#ffc209', '#0094f0', '#d2e2ff']);
    });
  }

  initBarChartData(): void {
    // 农业用水&生态用水
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: 28}).subscribe(res => {
      const legendData = ['农业用水', '生态用水'];
      const nyysData = [];
      const syysData = [];
      const xAxisData = [];
      res.map(item => {
        nyysData.push(item.nyVal);
        syysData.push(item.stVal);
        xAxisData.push(item.name);
      });
      this.barChartOpt1 = {
        legend: {
          data: legendData
        },
        xAxis: {
          data: xAxisData
        },
        yAxis: [
          {
            name: '亿方',
          },
        ],
        series: [
          {
            name: '农业用水',
            type: 'bar',
            barWidth: 10,
            itemStyle: {
              emphasis: {
                barBorderRadius: [5, 5, 0, 0]
              },
              normal: {
                barBorderRadius: [5, 5, 0, 0]
              }
            },
            data: nyysData
          },
          {
            name: '生态用水',
            type: 'bar',
            barWidth: 10,
            itemStyle: {
              emphasis: {
                barBorderRadius: [5, 5, 0, 0]
              },
              normal: {
                barBorderRadius: [5, 5, 0, 0]
              }
            },
            data: syysData
          }
        ]
      };
    });

    // 生活用水
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: 30}).subscribe(res => {
      const yAxisData = [];
      const seriesData = [];
      res.map(item => {
        yAxisData.unshift(item.name);
        seriesData.unshift(item.val);
      });
      this.baseBarChartOption2 = {
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 30,
          left: '3%',
          right: 50,
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            name: '亿m³',
            type: 'value'
          }
        ],
        yAxis: [
          {
            type: 'category',
            data: yAxisData,
          }
        ],
        series: [
          {
            name: '生活用水',
            type: 'bar',
            label: {
              show: true,
              position: 'inside'
            },
            data: seriesData
          }
        ]
      };
    });

  }

  getPieChartData(data, seriesName, title, unit, total, color): any {
    return {
      title: {
        text: [
          '{value|' + total + '}',
          '{value|' + unit + '}'
        ].join('\n')
      },
      color: color,
      legend: {
        data: data.map(item => {
          return item.name;
        }),
        formatter: name => {
          const target = _.find(data, o => {
            return o.name === name;
          }).totalVal;
          return name + ' ' + ((target / total) * 100).toFixed(2) + '%';
          // return name + ' ' + target + unit +  '' + ((target / total) * 100).toFixed(2) + '%';
        }
      },
      series: [
        {
          name: seriesName,
          label: {
            normal: {
              formatter: [
                '{name|{b}}',
                '{value|{c}}',
                '{value|' + unit + '}'
              ].join('\n')
            }
          },
          data: data.map(item => {
            return {
              value: item.totalVal,
              name: item.name
            };
          })
        }
      ]
    };
  }

  getPieChartData2(data, seriesName, title, unit, total, color): any {
    return {
      title: {
        text: [
          '{value|' + total + '}',
          '{value|' + unit + '}'
        ].join('\n')
      },
      color: color,
      legend: {
        data: data.map(item => {
          return item.name;
        }),
        formatter: name => {
          const target = _.find(data, o => {
            return o.name === name;
          }).useVal;
          return name + ' ' + ((target / total) * 100).toFixed(2) + '%';
          // return name + ' ' + target + unit +  '' + ((target / total) * 100).toFixed(2) + '%';
        }
      },
      series: [
        {
          name: seriesName,
          label: {
            normal: {
              formatter: [
                '{name|{b}}',
                '{value|{c}}',
                '{value|' + unit + '}'
              ].join('\n')
            }
          },
          data: data.map(item => {
            return {
              value: item.useVal,
              name: item.name
            };
          })
        }
      ]
    };
  }


  getTableData(): any {
    // 生活用水
    this.fetchService.post('sys/sysApiInfo/queryApiData', {apicode: 29}).subscribe(res => {
      this.gyysTableData = res;
    });

  }
}
